"use client";

import { useState, useEffect, useCallback } from "react";
import { Button } from "@/components/ui/button";
import { useSearchParams, useRouter } from "next/navigation";
import { toast } from "sonner";

import EmptyState from "@/components/EmptyState";
import EditModal from "@/components/EditModal";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import {DateTimePicker} from "@/components/DateTimePicker";
import CommonSelector from "@/components/CommonSelector";
import { Label } from "@/components/ui/label";
import { format, subDays, addDays } from "date-fns";
import AppointmentForm from "./AppointmentForm";
import EditAppointmentForm from "./EditAppointmentForm";
import { Badge } from "@/components/ui/badge";

export default function Client({
  campuses,
  listAppointments,
  confirmAppointment,
  cancelAppointment,
  getCourts,
  getAllUsers,
  addAssistantCoach,
  removeAssistantCoach,
  addClientWithPackage,
  removeClientWithPackage,
  getCoursePackages,
}) {
  const STATUS = [
    { value: 'pending', label: '待核销' },
    { value: 'inactive', label: '已核销' },
    { value: 'cancelled', label: '已取消' },
  ]
  const [appointments, setAppointments] = useState([]);

  const searchParams = useSearchParams();
  const router = useRouter();
  const initialAppointmentId = searchParams.get('appointment_id') || "";

  const [appointment_id] = useState(initialAppointmentId);

  const [coach_id, setCoachId] = useState(null);
  const [coaches, setCoaches] = useState([]);
  const [branch_campus_id, setBranchCampusId] = useState("");
  const [courts, setCourts] = useState([]);
  const [court_id, setCourtId] = useState("");
  const [status, setStatus] = useState("");
  const [start_time_from, setStartTimeFrom] = useState(initialAppointmentId ? subDays(new Date(), 30) : subDays(new Date(), 1));
  const [start_time_to, setStartTimeTo] = useState(initialAppointmentId ? addDays(new Date(), 30) : addDays(new Date(), 1));

  const handleClear = useCallback(() => {
    setCoachId(null);
    setBranchCampusId("");
    setCourtId("");
    setStatus("");
    setStartTimeFrom(subDays(new Date(), 1));//yesterday
    setStartTimeTo(addDays(new Date(), 1));//tomorrow
  }, []);

  const handleSearch = useCallback(async () => {
    const appointmentsList = await listAppointments({
      appointment_id,
      coach_id,
      branch_campus_id,
      court_id,
      status,
      start_time_from,
      start_time_to,
    });
    const filtered = appointment_id ? appointmentsList.filter(a => String(a.id) === String(appointment_id)) : appointmentsList;
    console.log("search appointments", filtered);
    setAppointments(filtered);
  }, [listAppointments, appointment_id, coach_id, branch_campus_id, court_id, status, start_time_from, start_time_to]);

  const handleGetCourts = useCallback(async () => {
    const courts = await getCourts({ status: 'active', branch_campus_id });
    setCourts(courts);
  }, [getCourts, branch_campus_id]);

  const handleGetCoaches = useCallback(async () => {
    const coaches = await getAllUsers({
      role: "coach",
      status: 'active',
      branch_campus_id,
    });
    setCoaches(coaches);
  }, [getAllUsers, branch_campus_id]);

  useEffect(() => {
    handleGetCourts();
    handleGetCoaches();
  }, [branch_campus_id, handleGetCourts, handleGetCoaches]);

  useEffect(() => {
    handleSearch();
  }, [handleSearch]);

  const handleCancelSuccess = useCallback(() => {
    handleSearch(); // 刷新列表

    // 显示 Sonner toast
    toast("预约已成功取消", {
      description: "3 秒后可以返回预约页面",
      action: {
        label: "返回预约页面",
        onClick: () => {
          router.push('/appointment');
        },
      },
      duration: 5000, // 3秒后自动消失
    });
  }, [handleSearch, router]);

  const AppointmentList = ({ appointments }) => {
    if (appointments.length === 0) {
      return (
        <EmptyState message="当前没有搜索到任何预约。" />
      );
    }
    return (
      <div className="grid grid-cols-1 md:grid-cols-3 gap-2">
        {appointments.map((appointment) => (
          <AppointmentItem key={appointment.id} appointment={appointment} />
        ))}
      </div>
    );
  };

  const AppointmentItem = ({ appointment }) => {
    return (
      <div className="flex flex-row items-center gap-2">
        <Card className="w-full">
          <CardHeader>
            <CardTitle className="text-lg font-bold flex flex-row justify-between gap-2">
              {coaches.find((coach) => coach.id === appointment.coach_id)?.name}
              {appointment.status === "pending" && (
  <>
    {/* 编辑按钮 */}
    <EditModal
      onSubmit={() => ({ success: true })} // 返回成功对象，因为编辑操作在子组件内部处理
      confirmButton="关闭"
      onSuccess={handleSearch}
      trigger={<Button variant="outline">编辑</Button>}
    >
      <EditAppointmentForm
        appointment={appointment}
        campuses={campuses}
        coaches={coaches}
        courts={courts}
        onSuccess={handleSearch}
        addAssistantCoach={addAssistantCoach}
        removeAssistantCoach={removeAssistantCoach}
        addClientWithPackage={addClientWithPackage}
        removeClientWithPackage={removeClientWithPackage}
        getCoursePackages={getCoursePackages}
        getAllUsers={getAllUsers}
      />
    </EditModal>

    {/* 原有的核销和取消按钮 */}
    <EditModal
      onSubmit={confirmAppointment}
      confirmButton="确认核销"
      onSuccess={handleSearch}
      trigger={<Button>核销</Button>}
    >
      <AppointmentForm
        appointment={appointment}
        campuses={campuses}
        coaches={coaches}
        courts={courts}
      />
    </EditModal>
    <EditModal
      onSubmit={cancelAppointment}
      confirmButton="确认取消"
      onSuccess={handleCancelSuccess}
      trigger={<Button variant="destructive">取消预约</Button>}
    >
      确认取消预约？
      <input type="hidden" name="appointment_id" value={appointment.id} />
    </EditModal>
  </>
)}
            </CardTitle>
          </CardHeader>
          <CardContent>
          {/* 校区 */}
          <div className="flex flex-row items-center gap-2">
            <Label className="w-24">校区：</Label>
            <p>{campuses.find((campus) => campus.id === appointment.branch_campus_id)?.name}</p>
          </div>
          {/* 场地 */}
          <div className="flex flex-row items-center gap-2">
            <Label className="w-24">场地：</Label>
            <p>{courts.find((court) => court.id === appointment.court_id)?.name}</p>
          </div>
          {/* 时间段 */}
          <div className="flex flex-row items-center gap-2">
              <Label className="w-24">时间段：</Label>
              <p>
                {format(appointment.start_time, "MM-dd HH:mm")} -{" "}
                {format(appointment.end_time, "MM-dd HH:mm")}
              </p>
            </div>
            <div className="flex flex-row items-center gap-2">
              <Label className="w-24">抽成比例：</Label>
              <p>{appointment.teaching_commission_rate}%</p>
            </div>
            {/* 备注 */}
            {appointment.memo && (
            <div className="flex flex-row items-center gap-2">
              <Label className="w-24">备注：</Label>
              <p className="whitespace-pre-line break-words flex-1">{appointment.memo}</p>
            </div>
            )}
             {/* 状态 */}
          <div className="flex flex-row justify-end gap-2">
            <Badge>{STATUS.find((status) => status.value === appointment.status)?.label}</Badge>
          </div>
          </CardContent>
        </Card>
      </div>
    );
  };

  return (
    <div className="space-y-4 flex-1 flex flex-col">
      <div className="flex justify-between items-center mb-4 flex-row">
        <h1 className="text-2xl font-bold">预约管理</h1>
      </div>
      {/* 搜索区域 */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div className="flex flex-row items-center gap-2">
          <Label className="w-24">校区ID：</Label>
          <CommonSelector
            items={campuses.map((campus) => ({
              value: campus.id,
              label: campus.name,
            }))}
            value={branch_campus_id}
            onValueChange={(e) => setBranchCampusId(e)}
          />
        </div>
          <div className="flex flex-row items-center gap-2">
            <Label className="w-24">场地ID：</Label>
            <CommonSelector
            items={courts.map((court) => ({
              value: court.id,
              label: court.name,
            }))}
            value={court_id}
              onValueChange={(e) => setCourtId(e)}
            />
          </div>
          <div className="flex flex-row items-center gap-2">
            <Label className="w-24">教练ID：</Label>
            <CommonSelector
            items={coaches.map((coach) => ({
              value: coach.id,
              label: coach.name,
            }))}
            value={coach_id}
            onValueChange={(e) => setCoachId(e)}
          />
        </div>
        <div className="flex flex-row items-center gap-2">
          <Label className="w-24">状态：</Label>
          <CommonSelector
            items={STATUS}
            value={status}
              onValueChange={(e) => setStatus(e)}
            />
          </div>
          <div className="flex flex-row items-center gap-2">
            <Label className="w-24">开始时间：</Label>
            <DateTimePicker
            className="w-full overflow-hidden"
            value={start_time_from}
              onChange={setStartTimeFrom}
            />
          </div>
          <div className="flex flex-row items-center gap-2">
            <Label className="w-24">结束时间：</Label>
            <DateTimePicker
            className="w-full overflow-hidden"
            value={start_time_to}
            onChange={setStartTimeTo}
            />
          </div>
          <div className="flex flex-row items-center gap-2">
            <Button onClick={handleClear}>清空</Button>
          <Button onClick={handleSearch}>搜索</Button>
        </div>
      </div>
      <AppointmentList appointments={appointments} />
    </div>
  );
}
